package com.hehe.conversion.hehemiddleware.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.hehe.conversion.hehemiddleware.model.req.old.ImgReqParam;
import com.hehe.conversion.hehemiddleware.model.req.old.EsbXmlRequest;
import com.hehe.conversion.hehemiddleware.model.AppHead;
import com.hehe.conversion.hehemiddleware.model.RootBody;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.RespBody;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.bl.BusinessLicenseIdnfRslt;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.EsbXmlResponse;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.bl.BusinessLicenseIdnfRsltItems;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.bl.ConuteShape;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.bl.DoBusTerm;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.bl.IdentPhtId;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.bl.ManagePlae;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.bl.ManageScopBody;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.bl.NamBody;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.bl.Operor;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.bl.PaInCapalBody;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.bl.RegistCapalBody;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.bl.RegistDt;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.bl.RegistNo;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.bl.RgstDt;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.bl.RgstOrg;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.bl.Type;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.bl.WherForEleBsnlic;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.bl.WherTranipt;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.idcard.IdCardIdnfRslt;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.idcard.IdnfContt;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.Response;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.ServiceResponse;
import com.hehe.conversion.hehemiddleware.model.resp.ocr.Result;
import com.hehe.conversion.hehemiddleware.model.resp.esbxml.bl.Ctgry;
import com.hehe.conversion.hehemiddleware.model.resp.ocr.bl.DetailItem;
import com.hehe.conversion.hehemiddleware.service.EsbXmlRequestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class EsbXmlRequestServiceImpl implements EsbXmlRequestService {

    @Value("${hehe.idcard.url}")
    private String idCardUrl;

    @Value("${hehe.business_license.url}")
    private String businessLicenseUrl;

    @Autowired
    RestTemplate restTemplate;

    @Value("${hehe.appkeyheader:App_key}")
    String appKeyHeaderName;

    @Value("${hehe.secretheader:App_secret}")
    String secretHeaderName;


    @Override
    public EsbXmlResponse handleIdCardRequest(EsbXmlRequest request) {
        log.info("EsbXmlRequestServiceImpl handleIdCardRequest");
        EsbXmlResponse result=new EsbXmlResponse();
        BeanUtil.copyProperties(request,result);
        try{
            //1.构建请求文件
            RootBody rootBody =new RootBody();
            rootBody.setBody(ImgReqParam.builder().imgAddr(request.getServiceBody().getBody().getImgAddr()).build());
            rootBody.setAppHead(AppHead.builder().appKey(request.getServiceHeader().getAppKey()).pswd(request.getServiceHeader().getPswd()).build());
            //rootRequest.setSysHead();
            //2.发送rsp请求
            log.info("EsbXmlRequestServiceImpl handleIdCardRequest sendRequest rootBody:{},",JSONObject.toJSONString(rootBody));
            /*HttpRequest httpRequest = HttpRequest.post(idCardUrl)
                    .contentType("application/json; charset=utf-8");
            httpRequest.body(JSONObject.toJSONString(rootBody));
            // 发送请求并接收响应
            HttpResponse response = httpRequest.execute();
            log.info("EsbXmlRequestServiceImpl handleIdCardRequest response status:{},result:{}",response.getStatus(),response.body());*/
            if (true) {
                //3.返回数据解析转换
                //RootBody<RespBody> responseRoot=JSONObject.parseObject(response.body(), RootBody.class);
                //本地JSON测试
                String readString = FileUtil.readString("D:\\idcard.txt", "UTF-8");
                RootBody responseRoot=JSONObject.parseObject(readString, RootBody.class);
                RespBody body = JSONObject.parseObject(responseRoot.getBody().toString(), RespBody.class);;
                if(body!=null&&body.getCode()==200){
                    Response<IdCardIdnfRslt> xmlResp=new Response<>();
                    xmlResp.setStatYard(body.getCode()+"");
                    xmlResp.setStatInfo(body.getMessage());
                    log.info("EsbXmlRequestServiceImpl handleIdCardRequest  result:{}",body.getResult());
                    Result rootResult = getJsonStr(body.getResult());
                    //身份证类型
                    IdCardIdnfRslt idCardIdnfRslt =new IdCardIdnfRslt();
                    idCardIdnfRslt.setIdentType(rootResult.getType());
                    idCardIdnfRslt.setIdentTypeChinDsc(rootResult.getTypeDescription());
                    idCardIdnfRslt.setOrialPictureTheDefonAngle(StrUtil.toStringOrNull(rootResult.getImageAngle()));
                    idCardIdnfRslt.setRevolveLaterTheImgWdDege(StrUtil.toStringOrNull(rootResult.getRotatedImageWidth()));
                    idCardIdnfRslt.setRevolveLaterTheImgHght(StrUtil.toStringOrNull(rootResult.getRotatedImageHeight()));
                    List<IdnfContt> idnfConttList=new ArrayList<>();
                    if(CollectionUtil.isNotEmpty(rootResult.getItemList())){
                        rootResult.getItemList().forEach(item->{
                            IdnfContt idnfContt=new IdnfContt();
                            idnfContt.setIdtyCerateConttItmTheNam(item.getKey());
                            idnfContt.setChinDsc(item.getValue());
                            idnfContt.setDsc(item.getDescription());
                            idnfContt.setConfefficient(StrUtil.toStringOrNull(item.getConfidence()));
                            idnfConttList.add(idnfContt);
                        });
                    }
                    idCardIdnfRslt.setIdnfConttList(idnfConttList);
                    xmlResp.setIdnfRslt(idCardIdnfRslt);
                    ServiceResponse serviceResponse=new ServiceResponse();
                    serviceResponse.setCode("COMPLETE");
                    serviceResponse.setDesc("交易成功");
                    result.getServiceHeader().setServiceResponse(serviceResponse);
                    result.getServiceBody().setResponse(xmlResp);
                }
            }
        }catch (Exception e){
            log.error("EsbXmlRequestServiceImpl handleIdCardRequest error",e);
        }
        return result;
    }

    /**
     * 读取OCR返回的result对象包含内容CDATA内容
     * @param str
     * @return
     */
    public Result getJsonStr(String str){
        // 使用正则表达式匹配CDATA内的内容
        Pattern pattern = Pattern.compile("<!\\[CDATA\\[(.*?)\\]\\]>");
        Matcher matcher = pattern.matcher(str);
        if (matcher.find()) {
            String jsonStr = matcher.group(1); // 提取匹配的字符串
            return JSONObject.parseObject(jsonStr, Result.class);
        }
        return null;
    }
    @Override
    public EsbXmlResponse handleBusinessLicenseRequest(EsbXmlRequest request) {
        log.info("EsbXmlRequestServiceImpl handleBusinessLicenseRequest");
        EsbXmlResponse result=new EsbXmlResponse();
        BeanUtil.copyProperties(request,result);
        try{
            RootBody rootBody =new RootBody();
            rootBody.setBody(ImgReqParam.builder().imgAddr(request.getServiceBody().getBody().getImgAddr()).imgBase64(request.getServiceBody().getBody().getImgBase64()).build());
            rootBody.setAppHead(AppHead.builder().appKey(request.getServiceHeader().getAppKey()).pswd(request.getServiceHeader().getPswd()).build());
            //rootRequest.setSysHead();
            //2.发送rsp请求
            log.info("EsbXmlRequestServiceImpl handleBusinessLicenseRequest sendRequest rootBody:{},",JSONObject.toJSONString(rootBody));
            HttpRequest httpRequest = HttpRequest.post(businessLicenseUrl)
                    .contentType("application/json; charset=utf-8");
            httpRequest.body(JSONObject.toJSONString(rootBody));
            // 发送请求并接收响应
            HttpResponse response = httpRequest.execute();
            log.info("EsbXmlRequestServiceImpl handleIdCardRequest response status:{},result:{}",response.getStatus(),response.body());
            //2.发送rsp请求
            log.info("EsbXmlRequestServiceImpl handleBusinessLicenseRequest sendRequest rootBody:{},",JSONObject.toJSONString(rootBody));
            if (response.isOk()) {
                //3.返回数据解析转换
                RootBody responseRoot=JSONObject.parseObject(response.body(), RootBody.class);
                //本地JSON测试
                //String readString = FileUtil.readString("D:\\test01.json", "UTF-8");
                //RootBody responseRoot=JSONObject.parseObject(readString, RootBody.class);
                RespBody body = JSONObject.parseObject(responseRoot.getBody().toString(), RespBody.class);;
                if(body!=null&&body.getCode()==200){
                    Response<BusinessLicenseIdnfRslt> xmlResp=new Response<>();
                    xmlResp.setStatYard(body.getCode()+"");
                    xmlResp.setStatInfo(body.getMessage());
                    log.info("EsbXmlRequestServiceImpl handleIdCardRequest  result:{}",body.getResult());
                    Result rootResult = getJsonStr(body.getResult());
                    BusinessLicenseIdnfRslt businessLicenseIdnfRslt=new BusinessLicenseIdnfRslt();
                    if(rootResult.getCategory()!=null){
                        Ctgry ctgry=new Ctgry();
                        ctgry.setKeyInfo1(rootResult.getCategory().getDETAILS_KEY1());
                        ctgry.setKeyInfo2(rootResult.getCategory().getDETAILS_KEY2());
                        ctgry.setKeyInfo3(rootResult.getCategory().getDETAILS_KEY3());
                        businessLicenseIdnfRslt.setCtgry(ctgry);
                    }
                    if(rootResult.getDetails()!=null){
                        BusinessLicenseIdnfRsltItems items=new BusinessLicenseIdnfRsltItems();
                        Map<String, DetailItem> details = rootResult.getDetails();
                        if(details.containsKey("BizLicenseIsCopy")){
                            WherTranipt wherTranipt=new WherTranipt();
                            wherTranipt.setWher(details.get("BizLicenseIsCopy").getValue());
                            wherTranipt.setConfefficient(details.get("BizLicenseIsCopy").getConfidence().toString());
                            wherTranipt.setFldDsc(details.get("BizLicenseIsCopy").getDescription());
                            items.setWherTranipt(wherTranipt);
                        }
                        if(details.containsKey("BizLicenseIsElectronic")){
                            WherForEleBsnlic wherForEleBsnlic=new WherForEleBsnlic();
                            wherForEleBsnlic.setWher1(details.get("BizLicenseIsElectronic").getValue());
                            wherForEleBsnlic.setConfefficient1(details.get("BizLicenseIsElectronic").getConfidence().toString());
                            wherForEleBsnlic.setConfefficient1(details.get("BizLicenseIsElectronic").getDescription());
                            items.setWherForEleBsnlic(wherForEleBsnlic);
                        }
                        if(details.containsKey("BizLicenseRegistrationCode")){
                            RegistNo registNo=new RegistNo();
                            registNo.setFldIdnfRslt2(details.get("BizLicenseRegistrationCode").getValue());
                            registNo.setConfefficient2(details.get("BizLicenseRegistrationCode").getConfidence().toString());
                            registNo.setFldDsc2(details.get("BizLicenseRegistrationCode").getDescription());
                            items.setRegistNo(registNo);
                        }
                        if(details.containsKey("BizLicenseSerialNumber")){
                            IdentPhtId identPhtId=new IdentPhtId();
                            identPhtId.setFldIdnfRslt3(details.get("BizLicenseSerialNumber").getValue());
                            identPhtId.setConfefficient3(details.get("BizLicenseSerialNumber").getConfidence().toString());
                            identPhtId.setFldDsc3(details.get("BizLicenseSerialNumber").getDescription());
                            items.setIdentPhtId(identPhtId);
                        }
                        if(details.containsKey("BizLicenseCompanyName")){
                            NamBody namBody=new NamBody();
                            namBody.setFldIdnfRslt4(details.get("BizLicenseCompanyName").getValue());
                            namBody.setConfefficient4(details.get("BizLicenseCompanyName").getConfidence().toString());
                            namBody.setFldDsc4(details.get("BizLicenseCompanyName").getDescription());
                            items.setNamBody(namBody);
                        }
                        if(details.containsKey("BizLicenseCompanyType")){
                            Type type=new Type();
                            type.setFldIdnfRslt5(details.get("BizLicenseCompanyType").getValue());
                            type.setConfefficient5(details.get("BizLicenseCompanyType").getConfidence().toString());
                            type.setFldDsc5(details.get("BizLicenseCompanyType").getDescription());
                            items.setType(type);
                        }
                        if(details.containsKey("BizLicenseAddress")){
                            ManagePlae managePlae=new ManagePlae();
                            managePlae.setFldIdnfRslt6(details.get("BizLicenseAddress").getValue());
                            managePlae.setConfefficient6(details.get("BizLicenseAddress").getConfidence().toString());
                            managePlae.setFldDsc6(details.get("BizLicenseAddress").getDescription());
                            items.setManagePlae(managePlae);
                        }
                        if(details.containsKey("BizLicenseComposingForm")){
                            ConuteShape conuteShape=new ConuteShape();
                            conuteShape.setFldIdnfRslt7(details.get("BizLicenseComposingForm").getValue());
                            conuteShape.setConfefficient7(details.get("BizLicenseComposingForm").getConfidence().toString());
                            conuteShape.setFldDsc7(details.get("BizLicenseComposingForm").getDescription());
                            items.setConuteShape(conuteShape);
                        }
                        if(details.containsKey("BizLicenseOwnerName")){
                            Operor operor=new Operor();
                            operor.setFldIdnfRslt8(details.get("BizLicenseOwnerName").getValue());
                            operor.setConfefficient8(details.get("BizLicenseOwnerName").getConfidence().toString());
                            operor.setFldDsc8(details.get("BizLicenseOwnerName").getDescription());
                            items.setOperor(operor);
                        }
                        if(details.containsKey("BizLicenseRegCapital")){
                            RegistCapalBody registCapalBody=new RegistCapalBody();
                            registCapalBody.setFldIdnfRslt9(details.get("BizLicenseRegCapital").getValue());
                            registCapalBody.setConfefficient9(details.get("BizLicenseRegCapital").getConfidence().toString());
                            registCapalBody.setFldDsc9(details.get("BizLicenseRegCapital").getDescription());
                            items.setRegistCapalBody(registCapalBody);
                        }
                        if(details.containsKey("BizLicensePaidInCapital")){
                            PaInCapalBody paInCapalBody=new PaInCapalBody();
                            paInCapalBody.setFldIdnfRslt10(details.get("BizLicensePaidInCapital").getValue());
                            paInCapalBody.setConfefficient10(details.get("BizLicensePaidInCapital").getConfidence().toString());
                            paInCapalBody.setFldDsc10(details.get("BizLicensePaidInCapital").getDescription());
                            items.setPaInCapalBody(paInCapalBody);
                        }
                        if(details.containsKey("BizLicenseStartTime")){
                            RegistDt registDt=new RegistDt();
                            registDt.setFldIdnfRslt11(details.get("BizLicenseStartTime").getValue());
                            registDt.setConfefficient11(details.get("BizLicenseStartTime").getConfidence().toString());
                            registDt.setFldDsc11(details.get("BizLicenseStartTime").getDescription());
                            items.setRegistDt(registDt);
                        }

                        if(details.containsKey("BizLicenseOperatingPeriod")){
                            DoBusTerm doBusTerm=new DoBusTerm();
                            doBusTerm.setFldIdnfRslt12(details.get("BizLicenseOperatingPeriod").getValue());
                            doBusTerm.setConfefficient12(details.get("BizLicenseOperatingPeriod").getConfidence().toString());
                            doBusTerm.setFldDsc12(details.get("BizLicenseOperatingPeriod").getDescription());
                            items.setDoBusTerm(doBusTerm);
                        }
                        if(details.containsKey("BizLicenseScope")){
                            ManageScopBody manageScopBody=new ManageScopBody();
                            manageScopBody.setFldIdnfRslt13(details.get("BizLicenseScope").getValue());
                            manageScopBody.setConfefficient13(details.get("BizLicenseScope").getConfidence().toString());
                            manageScopBody.setFldDsc13(details.get("BizLicenseScope").getDescription());
                            items.setManageScopBody(manageScopBody);
                        }
                        if(details.containsKey("BizLicenseRegistrationDate")){
                            RgstDt rgstDt=new RgstDt();
                            rgstDt.setFldIdnfRslt14(details.get("BizLicenseRegistrationDate").getValue());
                            rgstDt.setConfefficient14(details.get("BizLicenseRegistrationDate").getConfidence().toString());
                            rgstDt.setFldDsc14(details.get("BizLicenseRegistrationDate").getDescription());
                            items.setRgstDt(rgstDt);
                        }
                        if(details.containsKey("BizLicenseRegistrationAuthority")){
                            RgstOrg rgstOrg=new RgstOrg();
                            rgstOrg.setFldIdnfRslt15(details.get("BizLicenseRegistrationAuthority").getValue());
                            rgstOrg.setConfefficient15(details.get("BizLicenseRegistrationAuthority").getConfidence().toString());
                            rgstOrg.setFldDsc15(details.get("BizLicenseRegistrationAuthority").getDescription());
                            items.setRgstOrg(rgstOrg);
                        }
                        businessLicenseIdnfRslt.setIdnfRslt(items);
                    }
                    xmlResp.setIdnfRslt(businessLicenseIdnfRslt);
                    ServiceResponse serviceResponse=new ServiceResponse();
                    serviceResponse.setCode("COMPLETE");
                    serviceResponse.setDesc("交易成功");
                    result.getServiceHeader().setServiceResponse(serviceResponse);
                    result.getServiceBody().setResponse(xmlResp);
                }
            }

        }catch (Exception e){
            log.error("EsbXmlRequestServiceImpl handleBusinessLicenseRequest error",e);
        }
        return result;
    }

    /**
     * 获取图片流
     * @param imgAddr
     * @return
     * @throws IOException
     */
    public byte[] processImageUploadRequest(String imgAddr) throws IOException {
        log.info("EsbXmlRequestServiceImpl  processImageUploadRequest 获取图片流 imgAddr:{}",imgAddr);
        // 从URL下载图片并转换为二进制流
        byte[] imageBytes = restTemplate.getForObject(imgAddr, byte[].class);
        if (imageBytes == null) {
            throw new IOException("获取图片流失败");
        }
        return imageBytes;
    }


}
